package com.buaa.xxx0321;

import android.app.Service;
import android.content.Intent;
import android.os.Binder;
import android.os.IBinder;

public class MusicService extends Service {
    private int progress = 0;
    private boolean isPause = false;
    public MusicService() {
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        int action = intent.getIntExtra("action",-1);
        switch (action) {
            case 1:
                play();
                break;
            case 2:
                pause();
                break;
            case 3:
                resume();
                break;
        }
        return super.onStartCommand(intent, flags, startId);
    }

    @Override
    public IBinder onBind(Intent intent) {
        return new MyBinder();
    }
    public class MyBinder extends Binder {
        public int getProgress() {
            return progress;
        }
    }

    public void play() {
        Thread t = new Thread() {
            @Override
            public void run() {
                synchronized (MusicService.this) {
                    for(int i=0;i<=800;i++) {
                        if(isPause) {
                            try {
                                MusicService.this.wait();
                            } catch (InterruptedException e) {
                                e.printStackTrace();
                            }
                        }
                        try {
                            Thread.sleep(20);
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                        progress++;
                    }
                }
            }
        };
        t.start();
    }
    public void pause() {
        isPause = true;
    }
    public synchronized void resume() {
        isPause = false;
        notify();
    }
}
